package com.gzw.dms.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.adapter.FPOrderAdapter;
import com.gzw.dms.adapter.QscxAdapter1;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import com.gzw.dms.view.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectDriverOrderActivity extends BaseActivity {
    private ListView lv_order;
    private Context mContext;
    private ProgressDialog mProgressDialog;
    private TextView tv_seleteAll;
    private FPOrderAdapter orderAdapter;
    private int refresh = 0;
    private List<ShippingOrderInfo> shippingOrderInfo;
    private boolean isCheck = false;
    private android.support.v4.widget.SwipeRefreshLayout mSwipeLayout;
    private View progress;
    private String rownum = "100";
    private String rows = "0";
    private String shiping_order_goid = "";
    private String custom_name = "";
    private String shiping_order_num = "";
    private String send_time = "";
    private String send_mechanism = "";
    private String end_address = "";
    private String receipt_tel = "";
    private String receipt_name = "";
    private String end_time = "";
    private String end_mechanism = "";
    private Intent mIntetn;
    private String driver_id = "";
    private List<String> ls_map;
    private TextView tv_select;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_select_driver_order);

    }

    @Override
    protected void initViews() {
        lv_order = (ListView) findViewById(R.id.lv_order);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
        mSwipeLayout = (android.support.v4.widget.SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        progress = findViewById(R.id.include_pb);
        tv_select = (TextView) findViewById(R.id.tv_select);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    protected void initData() {
        mContext = this;
        ls_map = new ArrayList<>();
        mIntetn=getIntent();
        toolbar.setTitle("运单信息");
        setSupportActionBar(toolbar);
        driver_id = (String)mIntetn.getExtras().get("driver_id");
        ShowOrderTask showOrderTask = new ShowOrderTask();
        showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time,driver_id,end_mechanism);}

    @Override
    protected void initEvents() {
        tv_seleteAll.setOnClickListener(new myOnClick());
        lv_order.setOnItemClickListener(new mOnItemClick());
        tv_select.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());

        mSwipeLayout.setOnRefreshListener(new android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh = 1;
                ShowOrderTask showOrderTask = new ShowOrderTask();
                showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                        custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time,driver_id,end_mechanism);
            }
        });
    }


    class mOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ShippingOrderInfo shippingOrder = (ShippingOrderInfo) parent.getItemAtPosition(position);
            Intent mIntetn = new Intent();
            Bundle bundle = new Bundle();
            mIntetn.setClass(mContext, ShippingOrderDetailActivity.class);
            bundle.putSerializable("shippingOrder", shippingOrder);
            mIntetn.putExtra("driver_id", driver_id);
            mIntetn.putExtras(bundle);
            mIntetn.putExtra("fpstste","8");
            startActivityForResult(mIntetn, 1);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            refresh = 0;
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                    custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time,driver_id,end_mechanism);
        }else if(resultCode == 2){
            refresh = 0;
            String order_num1 = (String) data.getExtras().get("order_num");
            String shiping_order_goid1 = (String) data.getExtras().get("shiping_order_goid");
            String custom_name1
                    = (String) data.getExtras().get("custom_name");
            String receipt_name1
                    = (String) data.getExtras().get("receipt_name");
            String end_mechanism1
                    = (String) data.getExtras().get("end_mechanism");
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,order_num1,shiping_order_goid1,
                    custom_name1,receipt_name1,send_time,send_mechanism,end_address,receipt_tel,end_time,driver_id,end_mechanism1);
        }

    }

    /**
     * Created by Wangzhiqiang on 2015-10-11
     * 单击事件
     */
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_selectAll:
                    if (shippingOrderInfo != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < shippingOrderInfo.size(); i++) {
                                FPOrderAdapter.getIsSelected().put(i, true);
                            }
                            dataChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < shippingOrderInfo.size(); i++) {
                                if (FPOrderAdapter.getIsSelected().get(i)) {
                                    FPOrderAdapter.getIsSelected().put(i, false);
                                }
                            }
                            dataChanged();
                            isCheck = false;
                        }
                    }
                    break;
                case R.id.tv_select:
                    Intent mIntetn = new Intent();
                    mIntetn.setClass(mContext, TJSelectActivity.class);
                    mIntetn.putExtra("back","0");
                    startActivityForResult(mIntetn, 1);
                    break;
                default:
                    finish();
                    break;
            }

        }
    }


    // 刷新listview和TextView的显示
    private void dataChanged() {
        // 通知listView刷新
        orderAdapter.notifyDataSetChanged();
    }


    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            if (refresh == 0) {
//                mSwipeLayout.setRefreshing(true);
                mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
                mProgressDialog.setCancelable(true);
                mProgressDialog.setCanceledOnTouchOutside(false);

            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(true);
            }
        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("page", params[0]);
            map.put("row", params[1]);
            map.put("shiping_order_num",params[2]);
            map.put("shiping_order_goid",params[3]);
            map.put("custom_name",params[4]);
            map.put("receipt_name",params[5]);
            map.put("send_time",params[6]);
            map.put("send_mechanism",params[7]);
            map.put("end_address",params[8]);
            map.put("receipt_tel",params[9]);
            map.put("end_time",params[10]);
            map.put("driverId",params[11]);
            map.put("end_mechanism",params[12]);
            map.put("type","0");

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetFeiPeiOrderInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (refresh == 0) {
//                mSwipeLayout.setRefreshing(false);
                mProgressDialog.dismiss();

            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(false);
            }

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0){
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    shippingOrderInfo = JsonUtil.getPersons(successMsg, new TypeToken<List<ShippingOrderInfo>>() {
                    }.getType());
                    orderAdapter = new FPOrderAdapter(mContext, shippingOrderInfo);
                    lv_order.setAdapter(orderAdapter);
                }
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu_home; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_vehicle, menu);
        getMenuInflater().inflate(R.menu.menu_deleted, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_deleted:
                ls_map.clear();
                if (shippingOrderInfo != null){
                    for (int i = 0; i < shippingOrderInfo.size(); i++) {
                        if (orderAdapter.getIsSelected().get(i)) {
                            ls_map.add(shippingOrderInfo.get(i).getShiping_order_id());
                        }
                    }
                }
                if (ls_map.size() == 0) {
                    T.showShort(mContext, "请先选择要删除的运单!");
                } else {
                    FPOrderTask fpOrderTask = new FPOrderTask();
                    fpOrderTask.execute();
                }
                break;
        }
        return super.onOptionsItemSelected(item);

    }
    public class FPOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            String orders=ls_map.toString().substring(1,ls_map.toString().length()-1);
            String str1 = orders.replace(" ", "");
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("driverId",driver_id);
            map.put("orders",str1);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appDeleteShipOrderPage"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {

            mProgressDialog.dismiss();

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);

                    refresh = 0;
                    ShowOrderTask showOrderTask = new ShowOrderTask();
                    showOrderTask.execute(rownum, rows,shiping_order_num,shiping_order_goid,
                            custom_name,receipt_name,send_time,send_mechanism,end_address,receipt_tel,end_time,driver_id,end_mechanism);
//                    Intent mIntent = new Intent();
//                    //把返回数据存入Intent
//                    mIntent.putExtra("result", 1);
//                    //设置返回数据
//                    getActivity().setResult(1, mIntent);
//                    getActivity().finish();
                }
            }

        }
    }
}